import React, { useState, useEffect, forwardRef, useRef } from 'react'
import PropTypes from 'prop-types'
import { Popup, Icon, Keyboard, Input, Toast } from 'zarm'
import cx from 'classnames'
import s from './style.module.less'
import dayjs from 'dayjs'
import PopupDate from '../PopupDate'
import { get, post, typeMap } from '../../utils'
import CustomIcon from '@/components/CustomIcon'

const PopupAddBill = forwardRef(({ detail = {}, onReload }, ref) => {
  const id = detail && detail.id
  const [amount, setAmount] = useState('')
  const [show, setShow] = useState(false)

  const [date, setDate] = useState(new Date())
  const [payType, setPayType] = useState('expense')

  const [currentType, setCurrentType] = useState({})
  const [expense, setExpense] = useState([])
  const [income, setIncome] = useState([])

  const [remark, setRemark] = useState('')
  const [showRemark, setShowRemark] = useState(false)

  const dateRef = useRef()

  useEffect(() => {
    if (detail.id) {
      setPayType(detail.pay_type == 1 ? 'expense' : 'income')
      setCurrentType({
        id: detail.type_id,
        name: detail.type_name
      })
      setRemark(detail.remark)
      setAmount(detail.amount)
      setDate(dayjs(detail.date).$d)
    }
  }, [detail])

  useEffect(async () => {
    const { data } = await get('http://127.0.0.1:7001/api/type/list')
    console.log(data)
    const _expense = data.filter((i) => i.type == 1)
    const _income = data.filter((i) => i.type == 2)

    setExpense(_expense)
    setIncome(_income)
    if (!id) {
      setCurrentType(_expense[0])
    }
  }, [])

  const changeType = (type) => {
    setPayType(type)
  }

  const handleMoney = (value) => {
    value = String(value)
    console.log(value)

    if (value === 'delete') {
      let _amount = amount.slice(0, amount.length - 1)
      setAmount(_amount)
      return
    }
    if (value === 'ok') {
      addBill()
      return
    }
    // 当输入的值为 '.' 且 已经存在 '.'，则不让其继续字符串相加。
    if (value == '.' && amount.includes('.')) return
    // 小数点后保留两位，当超过两位时，不让其字符串继续相加。
    if (
      value != '.' &&
      amount.includes('.') &&
      amount &&
      amount.split('.')[1].length >= 2
    )
      return
    // amount += value
    setAmount(amount + value)
  }

  if (ref) {
    ref.current = {
      show: () => {
        setShow(true)
      },
      close: () => {
        setShow(false)
      },
    }
  }

  const selectDate = (val) => {
    setDate(val)
  }

  const addBill = async () => {
    if (!amount) return Toast.show('请输入金额')

    const params = {
      amount: Number(amount).toFixed(2),
      type_id: currentType.id,
      type_name: currentType.name,
      date: dayjs(date).format('YYYY-MM-DD hh:mm:ss'),
      pay_type: payType == 'expense' ? 1 : 2,
      remark: remark || ''
    }

    if (id) {
      params.id = id;
      // 如果有 id 需要调用详情更新接口
      const result = await post('http://127.0.0.1:7001/api/bill/update', params);
      Toast.show('修改成功');
    } else {
      const result = await post('http://127.0.0.1:7001/api/bill/add', params)

      // 重制数据
      setAmount('');
      setPayType('expense');
      setCurrentType(expense[0]);
      setDate(new Date());
      setRemark('');
      Toast.show('添加成功');
    }

    setShow(false);
    if (onReload) onReload();
  }

  return (
    <Popup
      visible={show}
      direction="bottom"
      destroy={false}
      mountContainer={() => document.body}
    >
      <div className={s.addWrap}>
        {/* 右上角关闭弹窗 */}
        <header className={s.header}>
          <span className={s.close} onClick={() => setShow(false)}>
            <Icon type="wrong" />
          </span>
        </header>
        {/* 「收入」和「支出」类型切换 */}
        <div className={s.filter}>
          <div className={s.type}>
            <span
              onClick={() => changeType('expense')}
              className={cx({
                [s.expense]: true,
                [s.active]: payType == 'expense',
              })}
            >
              支出
            </span>
            <span
              onClick={() => changeType('income')}
              className={cx({
                [s.income]: true,
                [s.active]: payType == 'income',
              })}
            >
              收入
            </span>
          </div>
          <div
            className={s.time}
            onClick={() => dateRef.current && dateRef.current.show()}
          >
            {dayjs(date).format('YYYY-MM')}{' '}
            <Icon className={s.arrow} type="arrow-bottom" />
          </div>
        </div>
        <div className={s.typeWarp}>
          <div className={s.typeBody}>
            {(payType == 'expense' ? expense : income).map((item) => (
              <div
                onClick={() => setCurrentType(item)}
                key={item.id}
                className={s.typeItem}
              >
                {/* 收入和支出的字体颜色，以及背景颜色通过 payType 区分，并且设置高亮 */}
                <span
                  className={cx({
                    [s.iconfontWrap]: true,
                    [s.expense]: payType == 'expense',
                    [s.income]: payType == 'income',
                    [s.active]: currentType.id == item.id,
                  })}
                >
                  <CustomIcon
                    className={s.iconfont}
                    type={typeMap[item.id].icon}
                  />
                </span>
                <span>{item.name}</span>
              </div>
            ))}
          </div>
        </div>
        <div className={s.remark}>
          {
            showRemark ? <Input
              autoHeight
              showLength
              maxLength={50}
              type="text"
              rows={3}
              value={remark}
              placeholder="请输入备注信息"
              onChange={val => setRemark(val)}
              onBlur={
                () => setShowRemark(false)
              }
            ></Input> : <span onClick={() => setShowRemark(true)}>{remark || '添加备注'}</span>
          }
        </div>
        <div className={s.money}>
          <span className={s.sufix}>¥</span>
          <span className={cx(s.amount, s.animation)}>{amount}</span>
        </div>
        <PopupDate ref={dateRef} onSelect={selectDate}></PopupDate>
      </div>
      <Keyboard type="price" onKeyClick={(value) => handleMoney(value)} />
    </Popup>
  )
})

export default PopupAddBill
